package web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import domain.SystemAdministrator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * 系统管理员拦截器
 * 对访问路径进行登录校验
 *
 * @author zdc
 */

public class SystemAdministratorInterceptor implements HandlerInterceptor {

    private final static Log log = LogFactory.getLog(SystemAdministratorInterceptor.class);

    /**
     * 请求完成后调用
     *
     * @param request 请求对象
     * @param response 响应对象
     * @param obj handler对象
     * @param exception 异常对象
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj,
                                Exception exception) throws Exception {
        log.debug("3.Called after rendering the view");

    }

    /**
     * Controller处理之后、渲染视图之前调用
     *
     * @param request 请求对象
     * @param response 响应对象
     * @param obj handler对象
     * @param model 模型视图对象
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView model)
            throws Exception {
        log.debug("2.Called after handler method request completion, before rendering the view");

    }

    /**
     * Controller处理之前调用
     *
     * @param request 请求对象
     * @param response 响应对象
     * @param arg2 handler对象
     * @return 是否继续处理
     * @throws Exception 异常对象
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        log.debug("1.Called before handler method");
        //获取session
        HttpSession session = request.getSession();
        //判断session中是否有管理员数据，如果有，则返回ture，继续向下执行
        if (session.getAttribute("systemAdministrator") != null) {
            return true;
        }
        //没有管理员数据，跳转到登陆界面
        response.sendRedirect(request.getContextPath()+"/login");
        return false;
    }
}
